package com.taotao.common.service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.bean.HttpclientResult;

/**
 *	httpclient处理get\post请求的工具类 
 */
@Service
public class HttpClientService {

	//HttpClientService中要注入HttpClient对象，但是某些系统可能不需要，因此也需要按需注入
	@Autowired(required = false)
	private CloseableHttpClient httpclient;

	/**
	 * @Description: 无参的get请求
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @author mingxu
	 */
	public String doGet(String url) throws ClientProtocolException, IOException {

		String resultJsonDate = null;

		HttpGet httpGet = new HttpGet(url);
		//调用接口后响应对象 : 响应状态  响应内容
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200 响应状态码
			if (response.getStatusLine().getStatusCode() == 200) {
				//说明请求成功，能够正确得到响应结果
				resultJsonDate = EntityUtils.toString(response.getEntity(), "UTF-8");
			}

		} finally {
			if (response != null) {
				response.close();
			}
		}

		return resultJsonDate;
	}

	/**
	 * @Description:有参的get请求
	 * @param url
	 * @param params Map<参数名称，参数值> params
	 * @return
	 * @throws URISyntaxException
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @author mingxu
	 */
	public String doGetParam(String url, Map<String, String> params)
			throws URISyntaxException, ClientProtocolException, IOException {
		String resultJsonDate = null;
		// 定义请求的参数
		URIBuilder uriBuilder = new URIBuilder(url);
		//参数传递方式
		//        Map<String,String> params = null;
		if (params != null && !params.isEmpty()) {
			for (String key : params.keySet()) {
				uriBuilder.setParameter(key, params.get(key));
			}
		}
		//build方法创建出URI对象
		URI uri = uriBuilder.build();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(uri);
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultJsonDate = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}

		return resultJsonDate;
	}

	/**
	 * 无参的post
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public HttpclientResult doPost(String url) throws ClientProtocolException, IOException {

		HttpPost httpPost = new HttpPost(url);
		//模拟了浏览器来进行访问  
		httpPost.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpPost);
			// 判断返回状态是否为200
			int code = response.getStatusLine().getStatusCode();
			String data = EntityUtils.toString(response.getEntity(), "UTF-8");
			return new HttpclientResult(code, data);
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	/**
	 * 有参的post请求
	 * @param url
	 * @param params
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public HttpclientResult doPostParam(String url, Map<String, String> params)
			throws ClientProtocolException, IOException {
		// 创建http POST请求
		HttpPost httpPost = new HttpPost(url);
		if (params != null && !params.isEmpty()) {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
			for (String key : params.keySet()) {
				parameters.add(new BasicNameValuePair(key, params.get(key)));
			}
			// 构造一个form表单式的实体
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
			// 将请求实体设置到httpPost对象中    设置post请求提交的表单
			httpPost.setEntity(formEntity);
		}

		//模拟了浏览器来进行访问  
		httpPost.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = httpclient.execute(httpPost);
			// 判断返回状态是否为200
			int code = response.getStatusLine().getStatusCode();
			String data = EntityUtils.toString(response.getEntity(), "UTF-8");
			return new HttpclientResult(code, data);
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}
}
